#####################
# Sleep Project - Pedro Bessone, Gautam Rao, Heather Schofield, Frank Schilbach, and Mattie Toma
# Purpose: Replicates Figure 2d from the Appendix (Measuring and Increasing Sleep)
# Last edited: 07 May 2021
#####################

rm(list=ls())
if (!require("pacman")) install.packages("pacman")
pacman::p_load(tidyverse, rio, scales)

# My theme
mytheme = theme_bw() +
  theme(panel.grid.major.x = element_blank(),
        panel.grid.minor.x = element_blank(),
        panel.grid.minor.y = element_blank(),
        panel.border = element_blank(),
        axis.line = element_line(color = "black"),
        text =  element_text(size = 12),
        axis.text = element_text(color = "black"))

# Import data
df.raw = import("Datasets/firststage_dataset.dta") %>% as_tibble()

df = df.raw %>% 
  filter(post_treatment == 1 & at_present_check == 1) %>% 
  select(pid, day_in_study, nap_time_mins, treat_nap)  %>% 
  filter(treat_nap == 1) %>% 
  filter(day_in_study < 28) %>% 
  mutate(dum_sleep = 1*(nap_time_mins > 0))


df  %>% 
  ggplot(aes(x = nap_time_mins, y = ..count../sum(..count..))) +
  mytheme +
  geom_histogram(color = "white", fill = rgb(62, 97, 128, max = 255)) +
  labs(y = "Percentage",
       x = "Minutes napping") +
  scale_y_continuous(expand = c(0,0), label = percent_format(accuracy = 1)) +
  geom_vline(xintercept = round(mean(df$nap_time_mins, na.rm = T), 2), color = "red", lty = 2, size = 1) +
  annotate(geom = "text", label = paste0("Mean: ", round(mean(df$nap_time_mins, na.rm = T), 1)),
           x = round(mean(df$nap_time_mins, na.rm = T), 1) - 2.3, y = .11, color = "red")

ggsave("Output/Appendix/Figures/Figure_A2_hist_mins_naps.pdf")
